<template>
  <!--  机台产量查询-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" :rules="formRules" ref="searchForm" class="demo-form-inline">
        <el-form-item label="工厂/车间" style="width: 250px">
          <el-tree-select v-model="searchParam.organizationId" @change="handleOrganizationChange" :data="workRoomList"
                          check-strictly :props="{ children: 'sonList', label: 'orgName', value: 'id' }"/>
        </el-form-item>
        <el-form-item label="设备" style="width: 250px">
          <el-select v-model="searchParam.equipmentId" placeholder="请选择设备" clearable filterable>
            <el-option v-for="item in equipmentData" :key="item.id" :label="item.equipmentCode" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="物料">
          <el-input v-model="searchParam.materialNo" placeholder="请输入物料编码" clearable style="width: 200px"/>
        </el-form-item>
        <el-form-item label="时间区间" prop="times" style="width: 450px">
          <el-date-picker v-model="searchParam.times" type="datetimerange" start-placeholder="开始时间"
                          end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="submitForm()">查询</el-button>
          <el-button class="refreshBtn" :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <div class="pageTableButView">
          <el-button icon="Download" type="primary" :loading="downLoading" @click="handleExport"
                     style="margin-left: 10px;">导出
          </el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" border height="calc(100vh - 320px)">
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope"> {{ (pageSearch.current - 1) * pageSearch.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="equipmentCode" label="机台" align="center" min-width="200"/>
        <el-table-column prop="shiftName" label="班次" align="center" min-width="200"/>
        <el-table-column prop="basicUnit" label="时间段" align="center" min-width="300"
                         show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.startDateTime }} - {{ scope.row.endDateTime }}
          </template>
        </el-table-column>
        <el-table-column prop="equipmentType" label="设备类别" align="center" min-width="200"/>
        <el-table-column prop="materialNo" label="物料" align="center" min-width="200"/>
        <el-table-column prop="userNickname" label="操作员" align="center" min-width="200"/>
        <el-table-column prop="equipmentYield" label="生产数量" align="center" min-width="200"/>
        <el-table-column prop="passQuantity" label="良品数量" align="center" min-width="200"/>
        <el-table-column prop="failQuantity" label="不良品数量" align="center" min-width="200"/>
        <el-table-column prop="stopType" label="停机类型" align="center" min-width="200"/>
        <el-table-column prop="stopTime" label="停机时长(秒)" align="center" min-width="200"/>
        <el-table-column prop="repairersUserNickname" label="修模员" align="center" min-width="200"/>

      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="pageSearch.current" v-model:page-size="pageSearch.pageSize"
                       :page-sizes="[10, 20, 50, 100, 200, 500]" layout="total, sizes, prev, pager, next"
                       :total="pageTotal"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import {ref, onMounted} from 'vue';
import {ElMessage, ElForm} from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {Delete, Edit, Plus, Refresh, Search} from '@element-plus/icons-vue';
import dayjs from 'dayjs';
import axios from "axios";
import moment from "moment";

onMounted(() => {
  getList();
  getOption();
});

const searchForm = ref<InstanceType<typeof ElForm>>();

const pageSearch = ref({
  current: 1,
  pageSize: 10
});

const pageTotal = ref(null); // 页面总数
const searchParam = ref({
  times: []
});

const paginatedData = ref([]);
const workRoomList = ref([]); // 车间
const equipmentData = ref([]);

const formRules = ref({
  organizationId: [{required: true, message: '请选择工厂/车间', trigger: 'change'}],
  equipmentIds: [{required: true, message: '请选择设备', trigger: 'change'}]
});

const handleOrganizationChange = (value) => {
  axiosInstance.post('/api/basedataEquipment/getAll', {organizationId: value}).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }
    equipmentData.value = res.data;
  });
};

const getOption = () => {
  axiosInstance.post('/api/basedataOrganization/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        workRoomList.value = res.data;
      });
};
const materialProperData = ref([
  {name: '采购件', id: '0'},
  {name: '半成品', id: '1'},
  {name: '成品件', id: '2'},
  {name: '模具', id: '3'},
  {name: '刀具', id: '4'},
  {name: '备件', id: '5'},
  {name: '量具', id: '6'},
  {name: '虚拟件', id: '7'}
]);
// 获取列表接口
const getList = () => {
  if (searchParam.value.times) {
    searchParam.value.startDateTime = searchParam.value.times[0];
    searchParam.value.endDateTime = searchParam.value.times[1];
  }

  axiosInstance.post('/api/equipmentYieldHistory/getPage', {
    ...searchParam.value,
    times: undefined,
    ...pageSearch.value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        paginatedData.value = res.data.records;
        pageTotal.value = res.data.total;
      });
};

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e;
  getList();
};

const handleCurrentChange = (e) => {
  pageSearch.value.current = e;
  getList();
};

const downLoading = ref(false);

const apiPost = import.meta.env.VITE_API_PROXY_TARGET;

const handleExport = () => {
  if (searchParam.value.times) {
    searchParam.value.startDateTime = searchParam.value.times[0];
    searchParam.value.endDateTime = searchParam.value.times[1];
  }

  if (!searchParam.value.times || searchParam.value.times.length == 0) {
    ElMessage.error('请选择时间');
    return false;
  }
  downLoading.value = true;
  axios.post('/api/equipmentYieldHistory/exportExcel', {
    ...searchParam.value,
    ...pageSearch.value

  }, {
    timeout: 30000, // 与 axiosInstance 的 timeout 相同
    responseType: 'blob',
    headers: {
      BearerToken: localStorage.getItem('token') || undefined // 与请求拦截器中的设置相同
    }
  })
      .then(response => {
        console.log(response);
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        const formattedDate = moment().format('YYYYMMDD');
        link.setAttribute('download', '机台产量查询' + formattedDate + '.xlsx'); // 导出的格式一定要和接口返回的文件一致
        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
      })
      .finally(() => {
        downLoading.value = false;
      });
};
// 提交表单
const submitForm = () => {
  searchForm.value.validate((valid) => {
    if (valid) {
      getList();
    } else {
      ElMessage.error('请检查表单输入');
      return false;
    }
  });
};

// 重置搜索条件
const resetSearch = () => {


  pageSearch.value.current = 1;
  searchForm.value.clearValidate();
  searchParam.value = {
    times: [
      dayjs().subtract(1, 'month').format('YYYY-MM-DD HH:mm:ss'),
      dayjs().format('YYYY-MM-DD HH:mm:ss')
    ]
  };
  // submitForm()
};
</script>
<style scoped></style>